<template>
  <div class="app-wrapper">
    <headerTitle
      :titleList="titleList"
      :hideButton="hideButton"
      :btnTitle="'新增机构'"
      icon="iconfont icon-zuzhiqunzu"
      @handelClick="() => addOrUpdate()"
    />
    <div class="app-container">
      <div class="containerMain">
        <div class="container table-con">
<!--          <div class="search-item">-->
<!--            <div class="item-con">-->
<!--              <span>机构名称</span>-->
<!--              <el-input size="mini" class="item" v-model="searchform.organName" placeholder="请输入机构名称"></el-input>-->
<!--            </div>-->
<!--            <div class="item-con">-->
<!--              <el-button class="kyeup_search_btn" type="primary" size="mini" @click="() => fetchData()">查询</el-button>-->
<!--              <el-button type="default" size="mini" @click="() => reset()">重置</el-button>-->
<!--            </div>-->
<!--          </div>-->
          <el-table
            size="small"
            :header-cell-style="headerStyle"
            :data="list"
            row-key="id"
            :header-cell-class-name="cellStyle"
            default-expand-all
            :tree-props="{children: 'children'}"
            style="margin-top: 10px"
          >
            <el-table-column prop="name" label="机构名称"></el-table-column>
            <el-table-column prop="code" label="机构业务号"></el-table-column>
            <el-table-column prop="lever" label="机构等级" :formatter="leverFormatter"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope" v-if="scope.row.level!=1">
                <el-button size="small" type="text" @click="() => editBtn(scope.row)">编辑</el-button>
                <el-button size="small" type="text" v-if="scope.row.isDefault!='0'" @click="() => delFn(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="40%"
      :before-close="handleClose"
    >
      <!-- @close="resets" -->
      <el-form ref="checkForm" :model="form" :rules="rulesList">
        <el-form-item label="机构级别" :label-width="formLabelWidth" prop="level">
          <el-radio-group v-model="form.level" @change="changeLev" :disabled="!updateShow">
            <el-radio :label="2">二级机构</el-radio>
            <el-radio :label="3">三级机构</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="机构名称" :label-width="formLabelWidth" prop="name">
          <el-input style="width:300px;" size="small" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item
          label="上级机构"
          :label-width="formLabelWidth"
          v-show="updateShow && form.level==3 || (!updateShow && form.level==3)"
          prop="parentId"
        >
          <el-select
            :disabled="!updateShow"
            v-model="form.parentId"
            filterable
            placeholder="请选择"
            style="width:300px;"
            size="small"
          >
            <el-option v-for="(item, index) in entlist" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构业务号" :label-width="formLabelWidth" prop="code">
          <el-input :disabled="!updateShow" size="small" style="width:300px;" oninput="this.value=this.value.replace(/[^0-9]/g, '')" v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" v-if="updateShow" @click="checkVlue" size="mini">确 定</el-button>
        <el-button type="primary" v-else @click="updateFn" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/Headertitle/index";
import selectModule from "@/components/common/selectmodulecopy";
import inputModule from "@/components/common/inputmodule";
import { fetchLastOrgan, fetchAddOrgan, fetchEditData, fetchEditOrgan, fetchSubId, fetchThreeSubId, fetchTreeData, fetchDel } from "@/api/systemapi/organ";
import { translateDataToTree } from "@/utils";

export default {
  components: {
    HeaderTitle,
    selectModule,
    inputModule
  },
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: "目录",
        2: "菜单"
      };
      return typeMap[type];
    },
    statusFilter(status) {
      const statusMap = {
        1: "启用",
        2: "禁用"
      };
      return statusMap[status];
    },
    statusTypeFilter(status) {
      const statusMap = {
        1: "success",
        2: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      titleList: [{ title: "机构管理" }],
      treeData: null,
      list: null,
      listLoading: true,
      optionOrg: [], // 所属机构
      accountList: [],// 账号权限下拉数组
      organprops: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true
      },
      searchform: {
        organName: ""
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
      title: "",
      updateShow: false, // 新增编辑禁用
      form: {
        level: 2,
        name: "",
        // code: "",
        parentId: "",
        code: ""
      },
      rulesList: {
        name: [
          { required: true, message: "机构名称不能为空", trigger: "blur" },
          {
            min: 3,
            max: 32,
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{3,32}$/,
            message: "机构名称只支持3-32位中英文和数字填写",
            trigger: "blur"
          }
        ],
        code:[
          { required: true, message: "机构业务号不能为空"},
          ]

        // parentId: [
        //   { required: true, message: "上级机构不能为空", trigger: "change" }
        // ],
      },
      entlist: [],
      levelShow: "",// 记录当前登录的是几级机构
      hideButton: false,
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
  //  机构等级格式化
    leverFormatter(row, column){
      if(row.level === 1){
        return '一级机构'
      }
      if(row.level === 2){
        return '二级机构'
      }
      if(row.level === 3){
        return '三级机构'
      }
    },
    //表头背景颜色修改
    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == 0) {
        return "background:#F5F6FB;color:#666";
      }
    },
    cellStyle({row, column, rowIndex, columnIndex}) {
      console.log({row, column, rowIndex, columnIndex}, "cell")
      if(columnIndex==0){
        return "special-row";
      }
    },
    handleClose() {
      this.dialogFormVisible = false;
    },
    changeLev() {
      console.log(this.form.level,123)
      if(this.form.level==3){
        this.chooseFn();
      }
    },


    // 点击树形节点 ，过滤列表坐席
    filterDepart(data) {
      // this.fetchData(data.id);
    },
    fetchData() {
      fetchTreeData().then(response => {
        if(response.code==0){
          this.levelShow = response.data[0].level;
          this.levelShow=='3'?this.hideButton=true:this.hideButton=false;
          this.list = response.data;
          this.listLoading = false;
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
    },
    getThreeSubId() {},
    checkVlue() {
      this.$refs.checkForm.validate((valid) => {
        if (valid) {
          // this.form.parentId = "0";
          fetchAddOrgan({...this.form}).then(res => {
            if(res.code==0) {
              this.dialogFormVisible = false;
              this.fetchData();
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    updateFn() {
      this.$refs.checkForm.validate((valid) => {
        if (valid) {
           fetchEditOrgan({...this.form}).then(res => {
            if(res.code == 0) {
              this.dialogFormVisible = false;
              this.fetchData();
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
        }
      })
    },
    // 删除
    delFn(data) {
      this.$confirm(`${data.level==2?`是否确定删除二级机构${data.name}及其下属机构`:`是否确定删除三级机构${data.name}`}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          fetchDel({id: data.id}).then(response => {
            if (response.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.fetchData();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 新增
    addOrUpdate() {
      this.title = "新增机构";
      this.form = {
        level: 2,
        name: "",
        // code: "",
        parentId: "",
        code: ""
      },
      this.levelShow=='2'?this.form.level=3:this.form.level=2;
      this.updateShow = true;
      this.dialogFormVisible = true;
      this.chooseFn();
    },
    editBtn(data) {
      this.title = "编辑机构";
      this.updateShow = false;
      this.chooseFn();
      fetchEditData({id: data.id}).then(res => {
        this.dialogFormVisible = true;
        this.form = res.data;
      })
    },
    chooseFn() {
      fetchLastOrgan().then(res => {
        this.entlist = res.data;
      })
    },
    reset() {
      this.searchform.organName = "";
      this.fetchData();
    }
  }
};
</script>
<style lang="scss">
.el-button--mini, .el-button--small{
  font-size: 14px;
}
</style>
<style lang="scss" scoped>
.containerMain {
  .search-item {
    padding: 20px 10px;
    font-size: 14px;
    color: #666;
    display: flex;
    justify-content: space-between;
    .item-con {
      display: flex;
      span {
        display: inline-block;
        width: 60px;
        text-align: right;
        line-height: 28px;
        margin-right: 10px;
      }
    }
    .item {
      width: 180px;
      margin-right: 10px;
    }
  }
  .container {
    .div-tree {
      width: 250px;
    }
    .div-table {
      flex: 1;
      width: 100%;
      overflow: hidden;
      .el-table {
        height: 100%;
        width: 100%;
        overflow: auto;
      }
    }
    .el-row {
      height: 300px;
      .el-col {
        height: 100%;
        .div-tree {
          height: 90%;
          .el-tree {
            height: 100%;
            overflow-y: auto;
          }
        }
      }
    }
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.special-row th {
  padding-left: 20px;
}
</style>
